﻿using AutoMapper;
using BS.Infra;
using BS.Infra.Interface;
using MediatR;

namespace BS.Write.Api.Handler.Tranceabilty
{
    public class DelTranceCommandHandler : IRequestHandler<DelTranceShuoYuanCommand, ApiResult>
    {
        private readonly ItraceabilitableRepository _traceabilitableRepository;

        private readonly IMapper _mapper;

        private readonly ILogger<DelTranceCommandHandler> _logger;

        public DelTranceCommandHandler(ItraceabilitableRepository traceabilitableRepository, IMapper mapper, ILogger<DelTranceCommandHandler> logger)
        {
            _traceabilitableRepository = traceabilitableRepository;
            _mapper = mapper;
            _logger = logger;
        }
        public async Task<ApiResult> Handle(DelTranceShuoYuanCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var traceId =await _traceabilitableRepository.GetAsync(x=>x.TrId==request.TrId);
                if (traceId.TrId== null)
                {
                    return await Task.FromResult(ApiResult.Fail("删除失败，请稍后再试"));
                }
                traceId.IsDeleted = true;
                await _traceabilitableRepository.UpdateAsync(traceId);
                return await Task.FromResult(ApiResult.Ok(traceId));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "DelTranceCommandHandler");
                return await Task.FromResult(ApiResult.Fail(ex.Message));
            }
        }
    }
}
public class DelTranceShuoYuanCommand:IRequest<ApiResult>
{
    public int TrId { get; set; }
}